package com.kefu.robot.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.common.context.KefuContext;
import com.kefu.robot.mapper.RobotAidataDocMapper;
import com.kefu.robot.model.RobotAidataDoc;
import com.kefu.robot.vo.RobotAidataDocTypeSearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.robot.mapper.RobotAidataDocTypeMapper;
import com.kefu.robot.model.RobotAidataDocType;

import java.util.List;

/**
 * @author xiaoyu
 * @date 2023/11/03
 */
@Service
public class RobotAidataDocTypeService extends AbstractKefuService<RobotAidataDocType> {
    @Autowired
    protected RobotAidataDocTypeMapper robotAidataDocTypeMapper;

    @Autowired
    protected RobotAidataDocMapper robotAidataDocMapper;

    public boolean saveAidataDocType(RobotAidataDocType info) {
        int maxWeight = robotAidataDocTypeMapper.getMaxWeight(KefuContext.getKefuContext().getTenantId(), info.getParentId());
        info.setWeight(maxWeight + 1);
        return save(info);
    }

    public boolean removeAidataDocType(String id) {
        String tenantId = KefuContext.getKefuContext().getTenantId();
        List<RobotAidataDocType> robotAidataDocTypeList = robotAidataDocTypeMapper.selectList(Wrappers.lambdaQuery(RobotAidataDocType.class)
                .eq(RobotAidataDocType::getParentId, id)
                .eq(RobotAidataDocType::getTenantId, tenantId));
        List<RobotAidataDoc> robotAidataDocList = robotAidataDocMapper.selectList(Wrappers.lambdaQuery(RobotAidataDoc.class)
                .eq(RobotAidataDoc::getDocTypeId, id)
                .eq(RobotAidataDoc::getTenantId, tenantId));
        if (robotAidataDocTypeList.size() > 0) {
            throw new RuntimeException("此分类有子分类，不可删除！");
        } else if (robotAidataDocList.size() > 0) {
            throw new RuntimeException("此分类下有词条，不可删除！");
        } else {
            removeById(id);
        }
        return true;
    }

    public List<?> listTree(RobotAidataDocTypeSearchVo search) {
        List<RobotAidataDocType> robotAidataDocTypeList = robotAidataDocTypeMapper.selectList(search.lambdaQuery());
        List<TreeNode<String>> nodeList = CollUtil.newArrayList();
        for (RobotAidataDocType docType : robotAidataDocTypeList) {
            nodeList.add((new TreeNode<>(docType.getDocTypeId(), docType.getParentId(), docType.getName(), docType.getWeight())));
        }
        return TreeUtil.build(nodeList, "0");
    }

}